<?php
/**
 * User: @lixu
 * Date: 2019-08-12
 * Time: 14:34
 */

use Biz\model\designerAward\Sign as mSign;
use Biz\model\designerAward\User as mUser;
use Doraemon\model\Member as mMember;
use Doraemon\service\Login;
use Doraemon\service\User as sUser;
use Doraemon\tools\HhzClient as tHhzClient;
use Doraemon\tools\Log as tLog;
use EasyWeChat\Factory;
use Infinity\cache\designerVote\OutUser as cOutUser;
use Infinity\cache\designerVote\UserVoteNumber as cUserVoteNumber;
use Infinity\service\designerVote\Vote as sVote;
/**
 * @deprecated
 */
class VoteAction extends ActionPlugin
{

    const USER_LEVEL = self::LEVEL_NOTHING;

    public function main()
    {
        if (date('Y-m-d') >= cUserVoteNumber::VOTE_END_TIME) {
            throw new \Exception('投票时间已结束');
        }

        $uid = $this->checkType();

        $caseId = $this->getRequest()->getPost('id');
        if(!$caseId) {
            throw new \Exception('案例不存在');
        }
        $num = $this->getRequest()->getPost('num');
        if(!$num) {
            throw new \Exception('最少投票数为1');
        }

        $voteType = $this->getRequest()->getPost('vote_type'); // user 普通票 designer 设计师推荐票 owner 业主
        if(!$voteType) {
            throw new \Exception('投票类型不存在');
        }

        $userInfo = sUser::getBasicUserInfo($uid);

        $voteNumber = sVote::initUserVote($uid, $userInfo);

        $this->checkRequest($uid, $caseId, $num, $voteType, $userInfo, $voteNumber);

        $data = mSign::get('*', ['id' => $caseId]);
        if(!$data) {
            throw new \Exception('案例不存在');
        }

        // 如果$voteType 与 业主渠道不统一的话，抛出异常
        $types = mUser::get('types', ['uid' => $data['uid']]);
        if($types == 1 && $voteType == 'user') {
            tLog::designervote_vote_debug('类型错误，疑似刷票', ['uid' => $uid, 'id' => $caseId, 'type' => $types, 'vote_type' => $voteType]);
            throw new \Exception('投票异常');
        } elseif (($types == 2 || $types == 3) && $voteType == 'owner') {
            tLog::designervote_vote_debug('类型错误，疑似刷票', ['uid' => $uid, 'id' => $caseId, 'type' => $types, 'vote_type' => $voteType]);
            throw new \Exception('投票异常');
        }

        if($data['uid'] == $this->uid && $userInfo['type'] == 2) {
            throw new \Exception("不能给自己投票哦~ <br> 去看看其他你喜欢的作品吧");
        }

        $voteNum = sVote::updateCache($uid, $caseId, $num, $data['uid'], $voteType);

        $this->setSuccess(['vote_num' => $voteNum]);
        // 请求完成后记录log
        sVote::insertLog($uid, $num, $data, $voteType, $this->browserType);
    }

    /**
     * 验证请求的数据
     * @param $uid
     * @param $caseId
     * @param $num
     * @param $type
     * @param $voteType
     * @param $userInfo
     * @param $voteNumber
     * @throws Exception
     */
    private function checkRequest($uid, $caseId, $num, $voteType, $userInfo, $voteNumber)
    {
        if($voteType == 'user' || $voteType == 'owner') {
            if($num > 10) {
                throw new \Exception('每次最多投10票');
            }
        } else if ($voteType == 'designer') {
            if($num > 5) {
                throw new \Exception('每次最多投5票');
            }
        } else {
            throw new \Exception('投票类型不存在');
        }

        if(tHhzClient::$client_type == tHhzClient::BROWSERTYPE_WECHAT) {
            if($userInfo['user_quality']) {
                $userQuality = explode(' ', $userInfo['user_quality']);
                if(in_array(mMember::QUALITY_B1, $userQuality)) {
                    tLog::designervote_vote_debug('用户发起投票失败 原因：B1用户无法进行投票', ['uid' => $uid, 'id' => $caseId, 'num' => $num]);
                    throw new \Exception('账号异常，无法发起投票');
                }
            }

            if($voteType == cUserVoteNumber::TYPE_DESIGNER && $userInfo['type'] != mMember::AUTH_USER_DESIGNER) {
                tLog::designervote_vote_debug('用户发起投票失败 原因：非设计师用户投票设计师推荐榜单', ['uid' => $uid, 'id' => $caseId, 'num' => $num]);
                throw new \Exception('投票失败，只有设计师可以投推荐票');
            }
        }

        $voteNumber = $voteNumber[$voteType];
        if(!$voteNumber || $voteNumber <= 0 || $num > $voteNumber) {
            tLog::designervote_vote_debug('用户发起投票失败 原因：余票不足', ['uid' => $uid, 'id' => $caseId, 'num' => $num, 'real_num' => $voteNumber]);
            throw new \Exception('余票不足');
        }
    }

    public function checkType()
    {
        if($this->browserType == tHhzClient::BROWSERTYPE_WECHAT) {
            $openId = $this->getRequest()->getPost('openid');
            $accessToken = $this->getRequest()->getPost('access_token');
            tLog::debug('投票接口接收openid和access_token', [$openId, $accessToken]);
            // 走微信的验证逻辑

            if(!$openId) {
                tLog::debug('openid为空不存在', [$openId]);
                throw new \Exception('投票异常');
            }


            if(!$accessToken) {
                tLog::debug('accessToken不存在', [$accessToken]);
                throw new \Exception('投票异常');
            }

            $result = cOutUser::getItem($openId);
            if(!$result) {
                Login::checkWeixinAuth($accessToken, $openId);

                $config = [
                    'app_id' => 'wx8cfd0f432ddd6c4a',
                    'secret' => 'f2ade2c8485f7222e95acde04d1a8448'
                ];
                $app = Factory::officialAccount($config);
                $user = $app->user->get($openId);
                if($user['errcode'] != 0) {
                    tLog::debug('请求微信验证失败', [$user]);
                    throw new \Exception('账号异常');
                }
                cOutUser::setItem($openId, $openId);
            }
            $uid = $openId;
        } else if (tHhzClient::$client_type == tHhzClient::APPTYPE_IOS || tHhzClient::$client_type == tHhzClient::APPTYPE_ANDROID) {
            if(!$this->uid) {
                throw new \Exception('登录后才能操作哦！');
            }
            $uid = $this->uid;
        } else {
            throw new \Exception('请在好好住APP或者微信内打开页面!');
        }

        return $uid;
    }
}